import sys
import os

file_path = os.path.abspath(__file__)
end = file_path.index('qmt_auto_trade') + 17
project_path = file_path[0:end]
sys.path.append(project_path)


import config.config_service as config_service
from mk_common.component.db.SQLiteManager import SQLiteManager


def create_tables():
    config_info_dict = config_service.get_config_info()
    trader_db_name = config_info_dict.get('trader_db_name')

    with SQLiteManager(trader_db_name) as sq_lite_db:

        # 交易记录表
        stock_trade_record = config_info_dict.get('stock_trade_record')

        sq_lite_db.drop_table(stock_trade_record)
        if bool(1 - sq_lite_db.table_exists(stock_trade_record)):
            columns_def = {
                'id': 'TEXT PRIMARY KEY',
                'symbol': 'TEXT NOT NULL',
                'str_day': 'TEXT',
                'trade_price': 'REAL',
                'trade_money': 'REAL',
                'trade_volume': 'REAL',
                'trade_number': 'TEXT',
                'str_now_time': 'TEXT',
                'trade_type': "TEXT"
            }
            sq_lite_db.create_table(stock_trade_record, columns_def)

        sq_lite_db.create_index(stock_trade_record, "symbol", unique=False)
        sq_lite_db.create_index(stock_trade_record, "str_day", unique=False)

        # 交易日期
        trade_date_list = config_info_dict.get('trade_date_list')
        sq_lite_db.drop_table(trade_date_list)

        if bool(1 - sq_lite_db.table_exists(trade_date_list)):
            columns_def = {
                'id': 'TEXT PRIMARY KEY',
                'trade_date': 'TEXT NOT NULL'
            }
            sq_lite_db.create_table(trade_date_list, columns_def)
        sq_lite_db.create_index(trade_date_list, "trade_date", unique=False)

        # 持仓表
        self_position = config_info_dict.get('self_position')
        sq_lite_db.drop_table(self_position)
        if bool(1 - sq_lite_db.table_exists(self_position)):
            columns_def = {
                'id': 'INTEGER PRIMARY KEY AUTOINCREMENT',
                'symbol': 'TEXT NOT NULL',
                'name': 'TEXT',
                'str_day': 'TEXT',
                'open_position': 'REAL',
                'available_position': 'REAL',
                'frozen_position': 'REAL',
                'cost_price': 'REAL',
                'now_price': "REAL",
                'floating_profit_loss': 'REAL',
                'profit_loss_percent': "REAL",
                'flow_mv': 'REAL',
                'day_buy': "REAL",
                'day_sell': "REAL",
                'market': 'TEXT',

            }
            sq_lite_db.create_table(self_position, columns_def)

        sq_lite_db.create_index(self_position, "symbol", unique=False)
        sq_lite_db.create_index(self_position, "str_day", unique=False)


if __name__ == '__main__':
    create_tables()
